package com.yeskery.nut.bean.condition;

import com.yeskery.nut.annotation.condition.ConditionalOnProperty;
import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.core.Environment;
import com.yeskery.nut.scan.BeanAnnotationScanMetadata;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 环境参数值条件判断
 * @author sunjay
 * 2023/9/6
 */
public class OnPropertyCondition implements Condition {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(OnPropertyCondition.class.getName());

    @Override
    public boolean matches(NutApplication nutApplication, Collection<BeanAnnotationScanMetadata> beanAnnotationScanMetadata, Object conditionalAnnotation) {
        Environment environment = nutApplication.getNutConfigure().getEnvironment();
        ConditionalOnProperty conditionalOnProperty = (ConditionalOnProperty) conditionalAnnotation;
        String prefix = conditionalOnProperty.prefix().trim();
        for (String value : conditionalOnProperty.value()) {
            String key = prefix + value.trim();
            String propertyValue = environment.getEnvProperty(key);
            if (propertyValue == null) {
                if (conditionalOnProperty.matchIfMissing()) {
                    continue;
                } else {
                    if (logger.isLoggable(Level.FINEST)) {
                        logger.log(Level.FINEST, "Property Condition Not Match, Condition[" + this.getClass().getName()
                                + "], Expect Property[" + key + "=" + conditionalOnProperty.havingValue()
                                + "], Actual Property[" + key + "] Not Found.");
                    }
                    return false;
                }
            }
            if (!propertyValue.equals(conditionalOnProperty.havingValue())) {
                if (logger.isLoggable(Level.FINEST)) {
                    logger.log(Level.FINEST, "Property Condition Not Match, Condition[" + this.getClass().getName()
                            + "], Expect Property[" + key + "=" + conditionalOnProperty.havingValue()
                            + "], Actual Property[" + key + "=" + propertyValue + "].");
                }
                return false;
            }
        }
        return true;
    }
}
